<template>
  <div class="container">
    <div>
      <el-button type="primary"
                 @click="addRole"
                 class="btn">添加角色</el-button>
    </div>

    <el-table :data="role"
              style="width: 100%"
              border>
      <el-table-column align="center"
                       prop="name"
                       label="角色"
                       width="200">
        <template v-slot="{row}">
          <el-input v-if="row.isEdit"
                    v-model="row.editRow.name"></el-input>
          <span v-else>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       prop="state"
                       label="启用"
                       width="200">
        <!-- 自定义结构 -->
        <template v-slot="{row}">
          <el-switch v-if="row.isEdit"
                     active-color="#13ce66"
                     inactive-color="#ccc"
                     :active-value="1"
                     :inactive-value="0"
                     v-model="row.editRow.state"></el-switch>
          <span v-else>{{ row.state === 1 ?'启用':'未启用' }}</span>
        </template>

      </el-table-column>
      <el-table-column align="center"
                       prop="description"
                       label="描述">
        <template v-slot="{row}">
          <el-input v-if="row.isEdit"
                    type="textarea"
                    :rows="2"
                    v-model="row.editRow.description" />
          <span v-else>{{ row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center"
                       label="操作">
        <template v-slot="{row}">
          <div v-if="row.isEdit">
            <el-button type="primary"
                       @click="btnEditOK(row)">确定</el-button>
            <el-button @click="row.isEdit = false">取消</el-button>
          </div>
          <div v-else>
            <el-button type="text"
                       @click="confirmRole(row)">分配权限</el-button>
            <el-button type="text"
                       @click="editRole(row)">编辑</el-button>
            <!-- 删除气泡确认框 -->
            <el-popconfirm title="确定删除这一条数据吗"
                           @onConfirm="confirmDel(row.id)">

              <el-button type="text"
                         slot="reference">删除</el-button>
            </el-popconfirm>
          </div>

        </template>

      </el-table-column>
    </el-table>
    <el-row type="flex"
            justify="center"
            align="end"
            style="height: 60px;">

      <el-pagination :page-size="pageParams.pagesize"
                     :current-page="pageParams.page"
                     :total="pageParams.total"
                     @current-change="currentChange"
                     layout="prev, pager, next" />
    </el-row>
    <!-- 新增角色 -->
    <el-dialog title="新增角色"
               @close="close"
               :visible.sync="roleVisible">
      <el-form ref="roleForm"
               :model="roleForm"
               :rules="roleRules"
               label-width="120px">
        <el-form-item prop="name"
                      label="角色">
          <el-input v-model="roleForm.name"
                    style="width: 300px;"
                    size="mini"></el-input>
        </el-form-item>
        <el-form-item label="状态"
                      prop="state">
          <template>
            <el-switch active-color="#13ce66"
                       inactive-color="#ccc"
                       :active-value="1"
                       :inactive-value="0"
                       v-model="roleForm.state" />

          </template>
        </el-form-item>
        <el-form-item prop="description"
                      label="描述">
          <el-input v-model="roleForm.description"
                    type="textarea"
                    placeholder=""
                    rows="3"
                    style="width: 300px;"
                    size="mini"></el-input>
        </el-form-item>
        <el-form-item>
          <el-row type="flex"
                  justify="center">
            <el-col :span="12">
              <el-button size="mini"
                         type="primary"
                         @click="btnOK">确定</el-button>
              <el-button size="mini"
                         @click="close">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog :visible.sync="editRoleVisible"
               title="分配权限">
      <el-tree ref="permTree"
               node-key="id"
               :data="getPermissionList"
               :props="{label:'name'}"
               show-checkbox
               default-expand-all
               :default-checked-keys="permIds"
               check-strictly />
      <el-row type="flex"
              justify="center">
        <el-button type="primary"
                   @click="btnConfirmOK">确定</el-button>
        <el-button @click="editRoleVisible=false">取消</el-button>
      </el-row>
    </el-dialog>

  </div>
</template>
<script>
import { getRole, addRole, updateRole, delRole, getCfirmPermission, assignPerm } from '@/api/role';
import { getPermissionList } from '@/api/permission'
import { transListToTree } from '@/utils'
export default {
  name: 'Role',
  data () {
    return {
      role: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      roleVisible: false,
      roleForm: {
        name: '',
        state: 0,
        description: ''
      },
      roleRules: {
        name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      editRoleVisible: false,
      getPermissionList: [],
      currentRoleId: null,
      permIds: null,
    }
  },
  created () {
    this.getRole();
  },
  methods: {
    close () {
      this.$refs.roleForm.resetFields();
      this.roleVisible = false;
    },
    async getRole () {
      const { rows, total } = await getRole(this.pageParams);
      this.role = rows;
      this.pageParams.total = total;
      this.role.forEach(item => {
        // item.isEdit = false
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    currentChange (newPage) {
      this.pageParams.page = newPage;
      this.getRole(); // 重新加载角色数据
    },
    addRole () {
      this.roleVisible = true;
    },
    btnOK () {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          await addRole(this.roleForm)
          this.$message.success('添加成功');
          this.getRole();
          this.close();
        }
      })
    },
    editRole (row) {
      row.isEdit = true

      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async btnEditOK (row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ ...row.editRow, id: row.id })
        this.$message.success('修改成功')
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })

        this.getRole()
      } else {
        this.$message.warning('角色管理员不能为空')
      }

    },
    async confirmDel (id) {
      // console.log(id);
      await delRole(id)
      this.$message.success('删除成功')
      if (this.role.length === 1) {
        this.pageParams.page--
      }
      this.getRole()
    },
    async confirmRole (row) {


      this.currentRoleId = row.id
      this.getPermissionList = transListToTree(await getPermissionList(), 0)

      const { permIds } = await getCfirmPermission(this.currentRoleId)
      this.permIds = permIds
      this.editRoleVisible = true
    },
    async btnConfirmOK () {

      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })

      this.$message.success('分配成功')
      this.editRoleVisible = false
    }

  }
}
</script>
<style scoped>
.btn {
  margin: 10px;
}
</style>